package utils

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func InitConfig() {
	viper.AutomaticEnv()
	fmt.Println("config app inited")
	fmt.Println("config mysql:" + viper.GetString("MYSQL_HOST"))
	fmt.Println("config mysql:" + viper.GetString("MYSQL_PORT"))
	fmt.Println("config mysql:" + viper.GetString("MYSQL_USER"))
	fmt.Println("config mysql:" + viper.GetString("MYSQL_PASSWORD"))
	fmt.Println("config mysql:" + viper.GetString("MYSQL_DBNAME"))
}

func InitMySQL() (*gorm.DB, error) {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second, //慢sql阈值
			LogLevel:      logger.Info, //级别
			Colorful:      true,        //彩色
		},
	)

	db, err := gorm.Open(mysql.Open("root:123456@tcp(192.168.0.2:3306)/ginchat?charset=utf8mb4&parseTime=True&loc=Local"),
		&gorm.Config{Logger: newLogger})
	if err != nil {
		fmt.Println("数据库连接失败：", err)
		return nil, err
	}
	fmt.Println("数据库已连接：", viper.GetString("MYSQL_HOST"))
	return db, nil
}
